<template>
  <div class="comment-view">
    <u-comment-scroll :disable="disable" @more="more">
      <u-comment
        ref="commentRef"
        :config="configs"
        :show-size="2"
        page
        style="display: flex; flex-direction: column"
        relative-time
        @submit="submit"
        @like="like"
        @reply-page="replyPage"
        @report="report"
        @show-info="showInfo"
        @mention-search="mentionSearch"
        @operate="operate"
        @remove="remove"
      >
        <!-- <template #list-title>全部评论</template> -->
        <template #card="scope">
          <div class="user-card">
            <div class="user-avatar">
              <el-avatar style="margin-top: 5px" :size="40" fit="cover" :src="scope.avatar">
                <img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png" />
              </el-avatar>
            </div>
            <div class="user-content">
              <div class="user-info">
                <a href="" class="username" target="_blank">
                  <span class="name" style="max-width: 10em">{{ scope.username }}</span>
                  <span blank="true" class="rank">
                    <u-icon size="24" v-html="useLevel(scope.level)" />
                  </span>
                </a>
              </div>
              <div class="social-info">
                <a href="" class="attention">
                  <span>{{ scope.attention }}</span>
                  <span>关注</span>
                </a>
                <a href="" class="follower">
                  <span>{{ scope.follower }}</span>
                  <span>粉丝</span>
                </a>
                <a href="" class="like">
                  <span>{{ scope.like }}</span>
                  <span>获赞</span>
                </a>
              </div>
              <div class="card-btn">
                <el-button type="primary"> 关注 </el-button>
                <el-button>发消息</el-button>
              </div>
            </div>
          </div>
        </template>
        <template #operate="scope">
          <my-operate :comment="scope" @remove="remove" />
        </template>
        <u-comment-nav v-model="latest" @sorted="sorted" />
      </u-comment>
    </u-comment-scroll>
  </div>
</template>

<script setup lang="ts">
  import { reactive, ref, onMounted } from 'vue'
  import { UToast, ConfigApi, CommentApi, useLevel, ReplyPageParamApi, SubmitParamApi, throttle, CommentInstance } from 'undraw-ui'
  // 下载表情包资源emoji.zip https://gitee.com/undraw/undraw-ui/releases
  // static文件放在public下,引入emoji.ts文件可以移动到自定义位置
  import emoji from '@/assets/emoji'
  import { UComment, UIcon, UCommentNav } from 'undraw-ui'
  import { pageComment, saveComment, pageReply } from '@/api/comment'
  import { getCommentLikedById, liked } from '@/api/commentLike'
  import MyOperate from './component/operate.vue'

  defineOptions({ name: 'Comment' })
  const configs = reactive<ConfigApi>({
    user: {
      id: 1,
      username: '',
      avatar: 'https://static.juzicon.com/avatars/avatar-200602130320-HMR2.jpeg?x-oss-process=image/resize,w_100',
      // 评论id数组 建议:存储方式用户id和文章id和评论id组成关系,根据用户id和文章id来获取对应点赞评论id,然后加入到数组中返回
      likeIds: [],
    },
    emoji: emoji,
    comments: [],
    // showLevel: false,
    // showHomeLink: false,
    // showAddress: false,
    // showLikes: false
  })

  // 排序
  const latest = ref(true)
  const sorted = (latest: boolean) => {
    console.log(latest)
  }

  // 是否禁用滚动加载评论
  const disable = ref(false)
  const pageData = reactive({
    // 当前页数
    pageNum: 1,
    // 页大小
    pageSize: 3,
    // 评论总数量
    total: 30,
  })
  // 加载更多评论
  const more = () => {
    if (pageData.pageNum <= Math.ceil(pageData.total / pageData.pageSize)) {
      pageData.pageSize = pageData.pageSize + 3
      setTimeout(async () => {
        let comments = await getComments(pageData.pageNum, pageData.pageSize)
        configs.comments.push(...comments)
      }, 200)
    } else {
      disable.value = true
    }
  }

  // const userInfo = ref({} as any);

  // 用户信息是否加载
  const loading = ref(false)
  // 请求获取用户详细信息
  const showInfo = (uid: string, finish: Function) => {
    console.log(loading.value)
    loading.value = true
    console.log('获取用户信息: ' + uid)
    let userInfo
    setTimeout(() => {
      userInfo = {
        id: String(uid),
        username: '落🤍尘' + uid,
        avatar: 'https://static.juzicon.com/avatars/avatar-200602130320-HMR2.jpeg?x-oss-process=image/resize,w_100',
        level: 6,
        like: 36011,
        attention: 15,
        follower: 6878,
      }
      loading.value = false
      finish(userInfo)
    }, 200)
  }

  function toFormData(object: any) {
    const formData = new FormData()
    Object.keys(object).forEach((key) => {
      const value = object[key]
      if (Array.isArray(value)) {
        value.forEach((subValue, i) => formData.append(key + `[${i}]`, subValue))
      } else {
        formData.append(key, object[key])
      }
    })
    return formData
  }

  /**
   * 去除属性值为 null和undefined、''的数据
   * @param obj
   */
  function removeEmptyField(obj: any) {
    return Object.keys(obj)
      .filter((key) => obj[key] !== null && obj[key] !== undefined && obj[key] !== '')
      .reduce(
        (acc, key) => ({
          ...acc,
          [key]: obj[key],
        }),
        {},
      )
  }

  // 提交评论事件
  const submit = ({ content, parentId, files, finish }: SubmitParamApi) => {
    console.log('提交评论: ' + content, parentId)
    const formData = {
      articleId: 1,
      content: content,
      parentId: parentId,
      // files: files
    }
    saveComment(toFormData(removeEmptyField(formData))).then((res) => {
      finish(res.data as any)
      UToast({
        message: '评论成功!',
        type: 'info',
      })
    })

    // saveBlogComment(formData as CommentSave).then((res: any) => {
    //   finish(res.data as any)
    //   UToast({ message: '评论成功!', type: 'info' })
    //   // pageData.value = data.list;
    //   // total.value = data.total;
    // })
    // .finally(() => {
    //   loading.value = false;
    // });
  }

  // 删除评论
  // const remove = (id: string, finish: () => void) => {
  //   console.log('删除评论: ' + id);
  //   setTimeout(() => {
  //     finish();
  //     alert(`删除成功: ${id}`);
  //   }, 200);
  // };

  const commentRef = ref<CommentInstance>()

  // 删除评论
  const remove = (comment: CommentApi) => {
    setTimeout(() => {
      commentRef.value?.remove(comment)
    }, 200)
  }

  const _throttle = throttle((type: string, comment: CommentApi, finish: Function) => {
    if (type === '删除') {
      alert(`删除成功: ${comment.id}`)
      finish()
    } else if (type === '举报') {
      alert(`举报成功: ${comment.id}`)
    }
  })

  // 操作按钮事件
  const operate = (type: string, comment: CommentApi, finish: Function) => {
    _throttle(type, comment, finish)
  }

  // 举报用户
  const report = (id: string, finish: () => void) => {
    console.log('举报用户: ' + id)
    setTimeout(() => {
      finish()
      alert(`举报成功: ${id}`)
    }, 200)
  }

  // 点赞按钮事件
  const like = (id: string, finish: () => void) => {
    console.log('点赞: ' + id)
    liked({
      articleId: 1,
      commentId: id,
    }).then((res) => {
      finish()
    })
  }

  // 回复分页
  const replyPage = ({ parentId, pageNum, pageSize, finish }: ReplyPageParamApi) => {
    pageReply({
      url: `/${pageNum}/${pageSize}`,
      parentId: parentId,
    }).then((res) => {
      finish(res.data)
    })
  }
  // 提及@ 事件
  const mentionSearch = (val: string) => {
    configs.mention!.data = userArr.filter((v) => v.name.includes(val))
  }

  onMounted(() => {
    getComments(pageData.pageNum, pageData.pageSize)
    getLikes()
  })

  // 获取评论列表
  const getComments = async (pageNum, pageSize) => {
    const res = await pageComment({
      pageNum,
      pageSize,
      blogId: 1,
    })
    const data = res.data.list.map((item) => {
      return {
        ...item,
        articleId: item.blogId,
      }
    })
    configs.comments.push(...data)
    pageData.total = res.data.list.length
    return res.data
  }
  // 获取点赞信息
  const getLikes = async () => {
    getCommentLikedById(1).then((res) => {
      configs.user.likeIds = res.data
    })
  }

  const userArr = [
    {
      id: 1,
      name: '张三',
      avatar: 'https://gd-hbimg.huaban.com/cba6c7af94997ba172c32bbe668794553f29e91ef26f-qnroJ7_fw240webp',
    },
    {
      id: 2,
      name: '李四',
      avatar: 'https://gd-hbimg.huaban.com/d01263d11d07748a2193bbbdd3b9a0c8a4b062b9f39d-PKvV2t_fw240webp',
    },
    {
      id: 3,
      name: '王五',
      avatar: 'https://gd-hbimg.huaban.com/69d92bfbf36fc111e1f563403311e7943628c9fc108bf-6l34Pa_fw240webp',
    },
    {
      id: 4,
      name: '赵六',
      avatar: 'https://gd-hbimg.huaban.com/7f5c54a455f61f431ec1f7b7c0e583f4a725fb73adba-5DgU3q_fw240webp',
    },
    {
      id: 5,
      name: '孙七',
      avatar: 'https://gd-hbimg.huaban.com/edea85f44f3f8bce8d094ed78f390164a9eba229cb2e-1Lc22F_fw240webp',
    },
    {
      id: 6,
      name: '周八',
      avatar: 'https://gd-hbimg.huaban.com/c1b2131c6977e01a430d6575ba678a4afeabcad222605-UJUwwb_fw240webp',
    },
    {
      id: 7,
      name: '吴九',
      avatar: 'https://gd-hbimg.huaban.com/4942e77078bda39a458980049b528236bf79183814998-zVzEJv_fw240webp',
    },
    {
      id: 8,
      name: '郑十',
      avatar: 'https://gd-hbimg.huaban.com/628236086a2ca12d2074bdd29f496f38a4d0c06ae50f-Rj3vsO_fw240webp',
    },
    {
      id: 9,
      name: '王富贵',
      avatar: 'https://gd-hbimg.huaban.com/0108a6b65d211d3bc602bc0431e84b31f9e62ac08015f-JifENm_fw240webp',
    },
    {
      id: 10,
      name: '赵富贵',
      avatar: 'https://gd-hbimg.huaban.com/d9643d6181d506ccc159a940e11bdc6b9a2b53ae57139-pxAnk9_fw240webp',
    },
  ]
</script>

<style lang="scss" scoped>
  .user-card {
    display: flex;
    .user-content {
      flex: 1;
      margin-left: 16px;
      .user-info {
        .username {
          display: flex;
          align-items: center;
          text-decoration: none;
          .name {
            max-width: 10rem;
            font-weight: 500;
            font-size: 15px;
            color: #252933;
            line-height: 32px;
            margin-right: 4px;
          }
        }
      }
      .social-info {
        margin-bottom: 10px;
        a {
          text-decoration: none;
        }
        a:not(:first-child) {
          margin-left: 18px;
        }
        a span:last-child {
          margin-left: 3px;
          color: #9499a0;
        }
      }
    }
  }
</style>
